<template>
  <div class="pre-onboarding-container">
    <div class="page-header">
      <h2>预进件管理</h2>
      <p>管理商户预进件申请，审核商户资质和材料</p>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.merchantName"
            placeholder="商户名称"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.contactPerson"
            placeholder="联系人"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-col>
        <a-col :span="6">
          <a-select
            v-model:value="searchForm.status"
            placeholder="审核状态"
            allow-clear
            style="width: 100%"
          >
            <a-select-option
              v-for="status in statusOptions"
              :key="status.value"
              :value="status.value"
            >
              {{ status.label }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="filteredData"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag
              :color="statusOptions.find(s => s.value === record.status)?.color"
            >
              {{ statusOptions.find(s => s.value === record.status)?.label }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'documents'">
            <div class="documents-status">
              <a-tooltip title="营业执照">
                <a-tag :color="record.documents.businessLicense ? 'success' : 'error'">
                  执照
                </a-tag>
              </a-tooltip>
              <a-tooltip title="身份证">
                <a-tag :color="record.documents.idCard ? 'success' : 'error'">
                  身份证
                </a-tag>
              </a-tooltip>
              <a-tooltip title="银行账户">
                <a-tag :color="record.documents.bankAccount ? 'success' : 'error'">
                  银行
                </a-tag>
              </a-tooltip>
              <a-tooltip title="税务登记">
                <a-tag :color="record.documents.taxRegistration ? 'success' : 'error'">
                  税务
                </a-tag>
              </a-tooltip>
              <a-tooltip title="组织机构代码">
                <a-tag :color="record.documents.organizationCode ? 'success' : 'error'">
                  组织
                </a-tag>
              </a-tooltip>
            </div>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="handleView(record)"
              >
                查看
              </a-button>
              <a-button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleReview(record)"
              >
                审核
              </a-button>
              <a-button
                v-if="record.status === 'approved'"
                type="link"
                size="small"
                @click="handleChannelOnboarding(record)"
              >
                渠道进件
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="申请详情"
      :footer="null"
      width="800px"
    >
      <div v-if="selectedRecord" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="申请编号">
            {{ selectedRecord.id }}
          </a-descriptions-item>
          <a-descriptions-item label="商户名称">
            {{ selectedRecord.merchantName }}
          </a-descriptions-item>
          <a-descriptions-item label="联系人">
            {{ selectedRecord.contactPerson }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedRecord.contactPhone }}
          </a-descriptions-item>
          <a-descriptions-item label="联系邮箱">
            {{ selectedRecord.contactEmail }}
          </a-descriptions-item>
          <a-descriptions-item label="业务类型">
            {{ selectedRecord.businessType }}
          </a-descriptions-item>
          <a-descriptions-item label="注册地址" :span="2">
            {{ selectedRecord.registeredAddress }}
          </a-descriptions-item>
          <a-descriptions-item label="营业执照号">
            {{ selectedRecord.businessLicense }}
          </a-descriptions-item>
          <a-descriptions-item label="申请时间">
            {{ selectedRecord.applicationDate }}
          </a-descriptions-item>
                     <a-descriptions-item label="审核状态">
             <a-tag
               :color="statusOptions.find(s => s.value === selectedRecord?.status)?.color"
             >
               {{ statusOptions.find(s => s.value === selectedRecord?.status)?.label }}
             </a-tag>
           </a-descriptions-item>
          <a-descriptions-item label="审核时间">
            {{ selectedRecord.reviewDate || '未审核' }}
          </a-descriptions-item>
          <a-descriptions-item label="审核人员">
            {{ selectedRecord.reviewer || '未分配' }}
          </a-descriptions-item>
          <a-descriptions-item label="拒绝原因" v-if="selectedRecord.rejectReason">
            {{ selectedRecord.rejectReason }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2" v-if="selectedRecord.notes">
            {{ selectedRecord.notes }}
          </a-descriptions-item>
        </a-descriptions>

        <div class="documents-section">
          <h4>资料完整性检查</h4>
          <a-row :gutter="16">
            <a-col :span="8">
              <div class="document-item">
                <check-circle-outlined v-if="selectedRecord.documents.businessLicense" class="icon-success" />
                <close-circle-outlined v-else class="icon-error" />
                <span>营业执照</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="document-item">
                <check-circle-outlined v-if="selectedRecord.documents.idCard" class="icon-success" />
                <close-circle-outlined v-else class="icon-error" />
                <span>身份证</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="document-item">
                <check-circle-outlined v-if="selectedRecord.documents.bankAccount" class="icon-success" />
                <close-circle-outlined v-else class="icon-error" />
                <span>银行账户</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="document-item">
                <check-circle-outlined v-if="selectedRecord.documents.taxRegistration" class="icon-success" />
                <close-circle-outlined v-else class="icon-error" />
                <span>税务登记证</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="document-item">
                <check-circle-outlined v-if="selectedRecord.documents.organizationCode" class="icon-success" />
                <close-circle-outlined v-else class="icon-error" />
                <span>组织机构代码</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-modal>

    <!-- 审核弹窗 -->
    <a-modal
      v-model:open="reviewVisible"
      title="审核申请"
      @ok="handleReviewSubmit"
      @cancel="reviewVisible = false"
    >
      <div v-if="selectedRecord">
        <a-form
          :model="reviewForm"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
        >
          <a-form-item label="商户名称">
            <span>{{ selectedRecord.merchantName }}</span>
          </a-form-item>
          <a-form-item label="申请编号">
            <span>{{ selectedRecord.id }}</span>
          </a-form-item>
          <a-form-item label="审核结果" required>
            <a-radio-group v-model:value="reviewForm.result">
              <a-radio value="approved">通过</a-radio>
              <a-radio value="rejected">拒绝</a-radio>
              <a-radio value="incomplete">材料不全</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="拒绝原因"
            v-if="reviewForm.result === 'rejected'"
          >
            <a-textarea
              v-model:value="reviewForm.rejectReason"
              placeholder="请输入拒绝原因"
              :rows="3"
            />
          </a-form-item>
          <a-form-item label="审核备注">
            <a-textarea
              v-model:value="reviewForm.notes"
              placeholder="请输入审核备注"
              :rows="3"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import { preOnboardingData, statusOptions, type PreOnboardingApplication } from './data'

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const reviewVisible = ref(false)
const selectedRecord = ref<PreOnboardingApplication | null>(null)

// 搜索表单
const searchForm = reactive({
  merchantName: '',
  contactPerson: '',
  status: undefined
})

// 审核表单
const reviewForm = reactive({
  result: 'approved',
  rejectReason: '',
  notes: ''
})

// 表格列定义
const columns = [
  {
    title: '申请编号',
    dataIndex: 'id',
    key: 'id',
    width: 150,
    fixed: 'left'
  },
  {
    title: '商户名称',
    dataIndex: 'merchantName',
    key: 'merchantName',
    width: 180
  },
  {
    title: '联系人',
    dataIndex: 'contactPerson',
    key: 'contactPerson',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
    width: 120
  },
  {
    title: '业务类型',
    dataIndex: 'businessType',
    key: 'businessType',
    width: 100
  },
  {
    title: '申请时间',
    dataIndex: 'applicationDate',
    key: 'applicationDate',
    width: 150
  },
  {
    title: '审核状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '资料状态',
    dataIndex: 'documents',
    key: 'documents',
    width: 200
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
]

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 计算过滤后的数据
const filteredData = computed(() => {
  let data = [...preOnboardingData]

  if (searchForm.merchantName) {
    data = data.filter(item =>
      item.merchantName.toLowerCase().includes(searchForm.merchantName.toLowerCase())
    )
  }

  if (searchForm.contactPerson) {
    data = data.filter(item =>
      item.contactPerson.toLowerCase().includes(searchForm.contactPerson.toLowerCase())
    )
  }

  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }

  pagination.total = data.length
  return data
})

// 搜索
const handleSearch = () => {
  pagination.current = 1
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    merchantName: '',
    contactPerson: '',
    status: undefined
  })
  pagination.current = 1
}

// 查看详情
const handleView = (record: PreOnboardingApplication) => {
  selectedRecord.value = record
  detailVisible.value = true
}

// 审核申请
const handleReview = (record: PreOnboardingApplication) => {
  selectedRecord.value = record
  reviewForm.result = 'approved'
  reviewForm.rejectReason = ''
  reviewForm.notes = ''
  reviewVisible.value = true
}

// 提交审核
const handleReviewSubmit = () => {
  if (reviewForm.result === 'rejected' && !reviewForm.rejectReason) {
    message.error('拒绝时必须填写拒绝原因')
    return
  }

  // 这里应该调用API提交审核结果
  message.success('审核结果已提交')
  reviewVisible.value = false
}

// 渠道进件
const handleChannelOnboarding = (record: PreOnboardingApplication) => {
  message.info(`正在为商户 ${record.merchantName} 发起渠道进件申请`)
  // 这里可以跳转到渠道进件页面或者直接发起申请
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以从API加载数据
})
</script>

<style scoped>
.pre-onboarding-container {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
}

.search-bar {
  margin-bottom: 24px;
  padding: 20px;
  background: #fafafa;
  border-radius: 6px;
}

.table-container {
  margin-top: 16px;
}

.documents-status {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.documents-section {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.documents-section h4 {
  margin-bottom: 16px;
  font-size: 14px;
  font-weight: 600;
}

.document-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
}

.icon-success {
  color: #52c41a;
}

.icon-error {
  color: #ff4d4f;
}
</style>